package org.example.communication_room.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.example.communication_room.Controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

public class JwtUtil {

    private static final String KEY = "haha";
    private static final long ACCESS_TOKEN_EXPIRY = 1000 * 60 * 360; // 360分钟
    private static final long REFRESH_TOKEN_EXPIRY = 1000 * 60 * 60 * 24 *360; // 360天
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    // 生成accessToken
    public static String genAccessToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + ACCESS_TOKEN_EXPIRY))
                .sign(Algorithm.HMAC256(KEY));
    }

    // 生成refreshToken
    public static String genRefreshToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + REFRESH_TOKEN_EXPIRY))
                .sign(Algorithm.HMAC256(KEY));
    }


    // 验证token并返回业务数据
    // 验证token并返回业务数据，处理过期异常
    public static Map<String, Object> parseToken(String token) throws JWTVerificationException {
        try {
            return JWT.require(Algorithm.HMAC256(KEY))
                    .build()
                    .verify(token)
                    .getClaim("claims")
                    .asMap();
        } catch (JWTVerificationException exception) {
            if (exception instanceof TokenExpiredException) {
                throw new TokenExpiredException("Token过期",((TokenExpiredException) exception).getExpiredOn());
            } else {
                throw new JWTVerificationException("无效的Token");
            }
        }
    }
    // 从Token中获取用户ID
    public static String getUserIdFromToken(String token) throws JWTVerificationException {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(KEY)).build();
        DecodedJWT jwt = verifier.verify(token);
        return jwt.getClaim("userId").asString();
    }
}
